<?php

namespace app\model;

use think\Model;
use think\model\relation\HasMany;

class Area extends Model
{
    public function children(): HasMany
    {
        return $this->hasMany(self::class, 'parent', 'adcode');
    }

    public function tree($parent = 0): array
    {
        $data = $this->field("adcode,name,parent")->withCount(['children' => "child"])->where('parent', $parent)->cache("tree_city_$parent", 7 * 24 * 3600)->select()->toArray();
//        dd($data);
        if (!empty($data)) {
            foreach ($data as &$item) {
                $child = $item['child'];
                unset($item['child']);
                $item['children'] = $child > 0 ? $this->tree($item['adcode']) : [];
            }
        }
        return $data;
    }

    public function province(): array
    {
        return $this->where(['level' => 1])->column("id,adcode,name", "adcode");
    }

    public function city(): array
    {
        $data = $this->where('id', request()->param("id"))->find();
        if (empty($data)) throw new \Exception("没有城市信息");
        if (preg_match("/^(北京|上海|天津|重庆).*/", $data['name']) && $data['level'] == 2) {
            $child = $this->where('parent', $data['adcode'])->with(['children' => function ($query) {
                $query->field("id,adcode,name");
            }])->find();
            if (empty($child)) throw new \Exception("没有城市信息");
            $children = $child->children()->toArray();
        } else {
            $children = $this->where('parent', $data['adcode'])->field("id,adcode,name")->select()->toArray();
        }
        return array_column($children, null, "adcode");
    }
}
